
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author Filip
 */
public class Main extends Applet implements KeyListener, ActionListener {

    private TextField textEntry;
    private Button speakButton;
    private Button textButton;
    private static InetAddress dns;

    public void init() {
        setBackground(Color.BLACK);
        textEntry = new TextField("Write your message here...", 100);
        speakButton = new Button("Voice");
        textButton = new Button("Text");
        add(textEntry);
        add(speakButton);
        add(textButton);
        speakButton.addKeyListener(this);
        textButton.addActionListener(this);
        textEntry.addKeyListener(this);
        speakButton.addActionListener(this);
        try {
            dns = Inet4Address.getByName("tkhduracell.dyndns.org");
            sendPush("ip: is watching you");
        } catch (Exception ex) {
            textEntry.setText(ex.toString());
        }

    }

    public void stop(){
        try {
            sendPush("ip: is NOT watching you anymore");
        } catch (IOException ex) {
            textEntry.setText(ex.toString());
        }
    }

    public void actionPerformed(ActionEvent e) {
        try {
            if (e.getSource() == speakButton) {
                String data = "speak:" + textEntry.getText();
                sendPush(data);
            } else if (e.getSource() == textButton) {
                String data = "ballon:" + textEntry.getText();
                sendPush(data);
                data = "message:" + textEntry.getText();
                sendPush(data);
            }
        } catch (ConnectException ce) {
            p("Remote computer isn't online or the connection was"
                    + " blocked by a firewall, " + ce.toString());
        } catch (Exception ex) {
            p(ex.toString());
        }
        repaint();
    }

    public void sendPush(String data) throws IOException, UnknownHostException {
        Socket s = new Socket(dns, 1337);
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        if (!(data == null || data.isEmpty())) {
            dos.writeUTF(data);
        }
        s.close();
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            actionPerformed(null);
        }
    }

    public void p(String s) {
        textEntry.setText(s);
    }

    public void keyTyped(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void keyReleased(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }


}
